package com.lonni.rpc.core.register.zk;

import com.alibaba.fastjson2.JSON;
import com.lonni.rpc.core.register.ServiceCache;
import com.lonni.rpc.core.register.ServiceDiscovery;
import com.lonni.rpc.core.register.model.Service;
import com.lonni.rpc.core.register.model.ServiceURL;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务发现接口
 *
 * @author: Lonni
 * @date: 2024/7/9 0009 15:37
 */
@Slf4j
public class ZookeeperDiscovery implements ServiceDiscovery {


    /**
     * 服务发现
     *
     * @param service
     * @return
     */
    @Override
    public List<ServiceURL> getService(Service service) throws Exception {
        List<ServiceURL> serviceURLS = ServiceCache.SERVICE_URLS.get(service);
        if (serviceURLS == null || serviceURLS.isEmpty()) {
            serviceURLS=new ArrayList<>();
            //从zk中获取,获取到的死 127.0.0.1:9898 地址
            String providerPath = ZKUtils.me.getProviderPath(
                    service.getInterfaceName(),
                    service.getGroup(),
                    service.getVersion());
            final List<String> strings = ZKUtils.me.client()
                    .getChildren()
                    .forPath(providerPath);
            log.info("获取zk服务列表,服务名称:{},版本:{},分组:{},列表:{}", service.getInterfaceName(), service.getVersion(), service.getGroup(), strings.toString());

            if (CollectionUtils.isEmpty(strings)) {
                log.info("没有找到已注册的提供者!");
                return null;
            }
            for (String address : strings) {
                String result = ZKUtils.me.getData(ZKUtils.me.getProviderPathForIpPort(service,address));
                ServiceURL serviceURL = buildServiceUrl(service, result);
                if (serviceURL!=null){
                    serviceURLS.add(serviceURL);
                }
            }
        }
        return serviceURLS;
    }


    ServiceURL buildServiceUrl(Service service, String data) {
        if (StringUtils.isBlank(data)) {
            return null;
        }
        return JSON.parseObject(data, ServiceURL.class);

    }
}
